using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MIMPGameLibrary;


namespace MIMP
{
    class LoadGameScreen : MenuScreen
    {
        public GameState loadedGameState;

        private string savedGamesDirectory;

        public LoadGameScreen(String savedGamesDirectory, bool isNewGame)
            : base(isNewGame ? "Choose a map to start the new game on" : "Choose a saved game to load")
        {
            this.savedGamesDirectory = savedGamesDirectory;
            
            DirectoryInfo dir = new DirectoryInfo(savedGamesDirectory);
            if (!dir.Exists) { throw new System.IO.DirectoryNotFoundException(); }

            foreach (FileInfo file in dir.GetFiles("*.mimp"))
            {
                string name = file.Name.ToString();
                name = name.Remove(name.Length - 5);
                MenuEntry entry = new MenuEntry(name);
                entry.Selected += new EventHandler<EventArgs>(LoadGame);
                MenuEntries.Add(entry);
            }
        }

        void LoadGame(object sender, EventArgs e)
        {
            MenuEntry selected = (MenuEntry)sender;
            string filename = savedGamesDirectory + selected.Text + ".mimp";
            IFormatter loadformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Stream loadStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);
            loadedGameState = (GameState)loadformatter.Deserialize(loadStream);
            loadStream.Close();
            IGameStateService gs = (IGameStateService)ScreenManager.Game.Services.GetService(typeof(IGameStateService));
            gs.RaiseLoadGameEvent(loadedGameState);
        }
    }
}
